# This file is part of Sonedyan.
#
# Sonedyan is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation;
# either version 3 of the License, or (at your option) any
# later version.
#
# Sonedyan is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public.
# If not, see <http://www.gnu.org/licenses/>.
#
# See http://igraph.wikidot.com/r-recipes for the original source code

tikz <- function (graph, layout) {
	## Here we get the matrix layout
	if (class(layout) == "function")
		layout <- layout(graph)
	
	layout <- layout / max(abs(layout))
	clos <- closeness(graph)
	
	##TikZ initialisation and default options (see pgf/TikZ manual)
	cat("\\tikzset{\n")
	# minimum size=0.8cm
	cat("\tnode/.style={circle,inner sep=1mm,fill=blue!20,text=black},\n")
	cat("\tnode0/.style={circle,inner sep=1mm,fill=red!20,text=black},\n")
	cat("\tnondirectional/.style={very thick,black},\n")
	cat("\tunidirectional/.style={thick, black,shorten >=2pt,-stealth},\n")
	cat("\tbidirectional/.style={very thick, black, shorten <=2pt, shorten >=2pt,stealth-stealth}\n")
	cat("}\n")
	cat("\n")
	
	##Size
	cat("\\begin{tikzpicture}[scale=5]\n")
	
	for (vertex in V(graph)) {
		label <- V(graph)[vertex]$name
		if (is.null(label))
			label <- ""
		
		##drawing vertices
		cat (sprintf ("\t\\node [node] (v%d) at (%f, %f)\t{%s};\n", vertex, layout[vertex+1,1], layout[vertex+1,2], label))
	}
	cat("\n")
	
	adj = get.adjacency(graph)
	bidirectional = adj & t(adj)
	
	if (!is.directed(graph)) ##undirected case
		for (line in 1:nrow(adj)) {
			for (col in line:ncol(adj)) {
				if (adj[line,col]&col>line) {
					cat (sprintf ("\t\\path [nondirectional] (v%d) edge (v%d);\n", line-1, col-1)) ##edges drawing
				}
			}
		}
	else ##directed case
		for (line in 1:nrow(adj)) {
			for (col in 1:ncol(adj)) {
				if (bidirectional[line,col]&line > col)
					cat (sprintf ("\t\\path [bidirectional] (v%d) edge (v%d);\n", line-1, col-1)) ##edges drawing
				else if (!bidirectional[line,col]&adj[line,col]) 
					cat (sprintf ("\t\\path [unidirectional] (v%d) edge (v%d);\n", line-1, col-1)) ##edges drawing
			}
		}
	
	cat("\\end{tikzpicture}\n")
}